package com.onetime.mall.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.onetime.mall.trading.dao.IdleItemDao;
import com.onetime.mall.trading.entity.IdleItemEntity;
import com.onetime.mall.trading.entity.LabelEntity;
import com.onetime.mall.trading.entity.UserEntity;
import com.onetime.mall.trading.service.IdleItemService;
import com.onetime.mall.trading.service.LabelService;
import com.onetime.mall.trading.service.UserService;
import com.onetime.mall.trading.utils.PageUtils;
import com.onetime.mall.trading.utils.Query;
import com.onetime.mall.trading.vo.ItemUserVo;
import com.onetime.mall.trading.vo.ProductAndCategoryVo;
import com.onetime.mall.trading.vo.StatisticsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author Lenovo
 */
@Service("idleItemService")
public class IdleItemServiceImpl extends ServiceImpl<IdleItemDao, IdleItemEntity> implements IdleItemService {

    @Autowired
    UserService userService;
    @Autowired
    LabelService labelService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String limit = (String) params.get("limit");
        String page = (String) params.get("page");
        IPage<IdleItemEntity> iPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));


        String status = params.get("status").toString();
        QueryWrapper<IdleItemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idle_status", status);

        String key = params.get("key").toString();
        if (!key.isEmpty()) {
            wrapper.and((i) -> i.eq("id", key).or().like("idle_name", key).or().like("idle_place", key));
        }

//        List<IdleItemEntity> idleItemEntities = baseMapper.selectList(wrapper);

        IPage<IdleItemEntity> page1 = this.page(iPage, wrapper);
        List<IdleItemEntity> records = page1.getRecords();
        List<ProductAndCategoryVo> collect = records.stream().map(item -> {
            ProductAndCategoryVo vo = new ProductAndCategoryVo();
            BeanUtils.copyProperties(item, vo);

            LabelEntity label = labelService.getById(item.getIdleLabel());
            String labelName = label.getName();
            vo.setCategoryName(labelName);

            /*String pictureList = item.getPictureList();
            String[] split = pictureList.split(",");
            String picUrl = split[0];
            vo.setPictureList(picUrl);*/
            return vo;
        }).collect(Collectors.toList());

        /*Query<IdleItemEntity> query = new Query<>();
        IPage<IdleItemEntity> iPage = this.page(query.getPage(params), new QueryWrapper<>());
        PageUtils pageUtils = new PageUtils(iPage);
        pageUtils.setList(collect);*/
        PageUtils pageUtils = new PageUtils(page1);
        pageUtils.setList(collect);

        return pageUtils;

        /*return new PageUtils(page);*/
    }

    @Override
    public PageUtils queryPageByCategory(Map<String, Object> params) {
        QueryWrapper<IdleItemEntity> wrapper = new QueryWrapper<>();
        String idleLabel = (String) params.get("idleLabel");
        wrapper.eq("idle_label", idleLabel).eq("idle_status", 1);

        List<ItemUserVo> goodsAndUsers = getGoodsAndUsers(wrapper);

        Query<IdleItemEntity> query = new Query<>();
        IPage<IdleItemEntity> iPage = this.page(query.getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(iPage);
        pageUtils.setList(goodsAndUsers);
        return pageUtils;
    }


    /**
     * 分类查询，分页
     * 同时查出闲置发布者的信息，代码结构与上面的类似，可封装优化，或改为join查询
     *
     * @return JSON
     */
    @Override
    public PageUtils queryPageAll(Map<String, Object> params) {

        String limit = (String) params.get("limit");
        String page = (String) params.get("page");
        String findValue = (String) params.get("findValue");

        IPage<IdleItemEntity> iPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<IdleItemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idle_status", 1);
        if (findValue != null) {
            wrapper.and(a -> a.like("idle_name", findValue).or().like("idle_details", findValue));
            /*wrapper.like("idle_name", findValue).or().like("idle_details", findValue);*/
        }

        /*定义分页类*/
        IPage<IdleItemEntity> page1 = this.page(iPage, wrapper);
        List<IdleItemEntity> records = page1.getRecords();
        List<ItemUserVo> goodsAndUsers = records.stream().map(item -> {
            ItemUserVo vo = new ItemUserVo();
            BeanUtils.copyProperties(item, vo);
            /*查询用户信息*/
            Long userId = item.getUserId();
            QueryWrapper<UserEntity> userWrapper = new QueryWrapper<>();
            userWrapper.eq("id", userId);
            UserEntity user = userService.getOne(userWrapper);

            vo.setUser(user);
            return vo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page1);
        pageUtils.setList(goodsAndUsers);
        return pageUtils;
    }

    /**
     * 查询闲置信息，同时查出发布者的信息
     *
     * @param id 商品id
     * @return 商品所有信息
     */
    @Override
    public ItemUserVo getIdleItem(Long id) {
        IdleItemEntity idleItem = baseMapper.selectById(id);
        if (idleItem != null) {
            ItemUserVo vo = new ItemUserVo();
            BeanUtils.copyProperties(idleItem, vo);
            Long userId = idleItem.getUserId();
            UserEntity user = userService.getById(userId);
            vo.setUser(user);
            return vo;
        }
        return null;
    }

    /**
     * 发布商品
     *
     * @param idleItemEntity 商品
     * @return true or false
     */
    @Override
    public boolean addIdleItem(IdleItemEntity idleItemEntity) {
        return baseMapper.insert(idleItemEntity) == 1;
    }

    /**
     * 查询用户发布的所有闲置
     *
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<IdleItemEntity> getAllIdelItem(Long userId) {
        QueryWrapper<IdleItemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).and(i -> i.ne("idle_status", 0));
        return baseMapper.selectList(wrapper);
    }

    /**
     * 更新商品
     *
     * @param idleItemEntity 新商品信息
     * @return true or false
     */
    @Override
    public boolean updateIdleItem(IdleItemEntity idleItemEntity) {
        return baseMapper.updateById(idleItemEntity) == 1;
    }

    @Override
    public PageUtils adminGetIdleListByPage(Map<String, Object> params) {
        Object status = params.get("status");
        QueryWrapper<IdleItemEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("idle_status", status);
        List<IdleItemEntity> idleItemEntities = baseMapper.selectList(wrapper);
        /*System.out.println("商品数量："+idleItemEntities.size());*/

        if (idleItemEntities != null) {
            List<ItemUserVo> collect = idleItemEntities.stream().map(item -> {
                ItemUserVo vo = new ItemUserVo();
                BeanUtils.copyProperties(item, vo);

                Long userId = item.getUserId();
                UserEntity user = userService.getById(userId);

                vo.setUser(user);
                return vo;
            }).collect(Collectors.toList());

            Query<IdleItemEntity> query = new Query<>();
            IPage<IdleItemEntity> iPage = this.page(query.getPage(params), wrapper);
            PageUtils pageUtils = new PageUtils(iPage);
            pageUtils.setList(collect);
            return pageUtils;
        }
        return null;
    }

    @Override
    public IdleItemEntity GetProductInformation(Long idleId) {
        IdleItemEntity entity = baseMapper.selectById(idleId);
        return entity;
    }

    /**
     * 统计商品类别数据
     *
     * @return 商品类别统计数据
     */
    @Override
    public List<StatisticsVo> getProductCategoryStatistics(Integer status) {
        List<Map<String, String>> maps = baseMapper.statistics(status);
        List<StatisticsVo> collect = maps.stream().map(item -> {

            String label = String.valueOf(item.get("label"));
            String count = String.valueOf(item.get("count"));
            LabelEntity labelEntity = labelService.getById(label);
            String name = labelEntity.getName();

            StatisticsVo vo = new StatisticsVo();
            vo.setName(name);
            vo.setValue(Long.valueOf(count));
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 批量改变商品状态
     *
     * @param collect
     */
    @Override
    public void changeByIds(List<Long> collect) {
        List<IdleItemEntity> entities = baseMapper.selectBatchIds(collect);
        entities.stream().map(item -> {
            Integer status = item.getIdleStatus();
            if (status == 1) {
                status = 2;
            } else if (status == 2) {
                status = 1;
            }
            item.setIdleStatus(status);
            baseMapper.updateById(item);
            return item;
        }).collect(Collectors.toList());
    }

    /**
     * @param wrapper
     * @return
     */
    public List<ItemUserVo> getGoodsAndUsers(QueryWrapper<IdleItemEntity> wrapper) {
        List<IdleItemEntity> idleItemEntities = baseMapper.selectList(wrapper);
        List<ItemUserVo> collect = idleItemEntities.stream().map(item -> {
            ItemUserVo vo = new ItemUserVo();
            BeanUtils.copyProperties(item, vo);

            Long userId = item.getUserId();
            QueryWrapper<UserEntity> userWrapper = new QueryWrapper<>();
            userWrapper.eq("id", userId);
            UserEntity user = userService.getOne(userWrapper);

            vo.setUser(user);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }


}